<?php
namespace aszx0413\yii2gii;

use yii\helpers\Inflector;

class Table
{
    /**
     * @var string 数据库表名
     */
    public $name = '';

    /**
     * @var string 数据库中文表名
     */
    public $nameCn = '';

    /**
     * @var Field[] 表字段数组
     */
    public $fields = [];

    /**
     * @var string 类名
     */
    public $class = '';

    /**
     * @var One[]
     */
    public $hasOneList = [];

    /**
     * @var Many[]
     */
    public $hasManyList = [];

    /**
     * 是否生成列表
     * @var bool
     */
    public $isList = true;

    /**
     * 是否生成表单
     * @var bool
     */
    public $isForm = true;

    /**
     * @var int
     */
    private $fieldRefMaxLen = 0;

    public function getFieldRefMaxLen()
    {
        foreach ($this->fields as $v) {
            if ($this->fieldRefMaxLen < strlen('string')) {
                $this->fieldRefMaxLen = strlen('string');
            }
        }
        foreach ($this->hasManyList as $v) {
            if ($this->fieldRefMaxLen < (strlen($v->relateTable->class) + 2)) {
                $this->fieldRefMaxLen = strlen($v->relateTable->class) + 2;
            }
        }
    }

    public function setName(string $name)
    {
        $this->name  = $name;
        $this->class = Inflector::camelize($name);
    }

    public function asProperty()
    {
        return lcfirst(Inflector::camelize($this->name));
    }

    /**
     * 获取 getXxx 中的 Xxx
     * @param $on
     * @return string
     */
    public function asGetXxx($on)
    {
        // 如果 $on='user_id' 则是 getUser
        // 如果 $on='xxx_user_id' 则是 getXxxUser
        $name = str_replace('_id', '', $on);

        return Inflector::camelize($name);
    }

    /**
     * 获取 getXxxList 中的 Xxx
     * @param $on
     * @return string
     */
    public function asGetXxxList($on)
    {
        // 如果 $on='user_id' 则是 getUserList
        // 如果 $on='xxx_user_id' 则是 getXxxUserList
        $name = str_replace('_id', '', $on);

        return Inflector::camelize($name);
    }
}
